home *** CD-ROM | disk | FTP | other *** search
/ Monster Media 1996 #15 / Monster Media Number 15 (Monster Media)(July 1996).ISO / internet / javnl006.zip / JAVNL006.TXT < prev   
Text File  |  1996-06-05  |  15KB  |  440 lines

  1. Issue #006
  2. June, 1996
  3.  
  4.  
  5. Contents:
  6.  
  7. JavaDoc
  8. Comparing C/C++ to Java Part 6 - Method Overloading
  9. Introduction to Applet Programming Part 2 - Drawing
  10. Performance - Primitive Types vs. Wrappers
  11.  
  12.  
  13. JAVADOC
  14.  
  15. You may have heard of the term "JavaDoc" in relation to Java.  What is
  16. this?  JavaDoc is a tool that comes with the Java Development Kit.
  17. It's used for preparing HTML (the language of the Web) documentation
  18. for Java classes.  That is, it generates HTML code that documents a
  19. class or package (set of related classes), including their methods,
  20. interfaces, exceptions, class hierarchy, and so on.
  21.  
  22. JavaDoc extracts structured comments from a Java source file.  For
  23. example:
  24.  
  25.         /**
  26.          * Create a hash table.
  27.          *
  28.          * @param       sz initial table size in hash slots (>= 1)
  29.          * @param       load_factor (average elements per slot)
  30.          *              (0.25 - 10.0)
  31.          * @param       growth_factor (how much to grow the table
  32.          *              when load factor is exceeded) (1.1 - 2.0)
  33.          * @exception   IllegalArgumentException for invalid arguments
  34.          */
  35.  
  36.         public Hash(int sz, float load_factor, float growth_factor)
  37.         {
  38.                 // stuff
  39.         }
  40.  
  41. This is documentation for a constructor for a hash table class.
  42. JavaDoc keys off of "/**" and tags like "@param".  Page 182 of David
  43. Flanagan's "Java in a Nutshell" (O'Reilly) describes the tags that can
  44. be used.
  45.  
  46. You can run JavaDoc on individual Java source files, or on whole
  47. packages.  It generates a set of HTML files that can be used on a Web
  48. page or with a Web browser whether connected to the Web or not.  The
  49. files have hyperlinks between related classes and methods, so that a
  50. user can navigate easily through the documentation.
  51.  
  52.  
  53. COMPARING C/C++ TO JAVA PART 6 - METHOD OVERLOADING
  54.  
  55. In both C++ and Java it's possible to have functions/methods with the
  56. same name as other functions.  For example, in C++ you can say:
  57.  
  58.         class A {
  59.         public:
  60.                 void f(int i) {}
  61.                 void f(char* s) {}
  62.         };
  63.  
  64. and the compiler will choose the right function based on the type of
  65. the argument given to f().  Java has a similar facility.
  66.  
  67. One question that naturally arises is how to choose the proper
  68. function or method to call.  For example, with this C++ code:
  69.  
  70.         void f(short s) {}
  71.  
  72.         void f(long l) {}
  73.  
  74. and a call:
  75.  
  76.         char c = 0;
  77.  
  78.         f(c);
  79.  
  80. it's not clear which of these functions to call, because a char could
  81. be promoted to either a short or a long (this particular call is in
  82. fact ambiguous in C++).
  83.  
  84. Java uses what is known as a "most specific" algorithm to figure out
  85. which method to call.  Before we explain what is meant by this, we
  86. need to talk a bit about assignment, namely, what sorts of types can
  87. be assigned to other types in Java.  Here is an example to illustrate
  88. this point:
  89.  
  90.         public class test1 {
  91.  
  92.                 public static void main(String args[])
  93.                 {
  94.                         short s = 0;
  95.                         int i = 0;
  96.                         float f = 0.0f;
  97.  
  98.                         i = s;          // OK
  99.                         f = i;
  100.  
  101.                         s = i;          // error
  102.                         i = f;
  103.  
  104.                         s = (short)i;   // OK but have to be careful
  105.                         i = (int)f;
  106.                 }
  107.  
  108.         }
  109.  
  110. We can assign shorter primitive types to longer ones, for example
  111. short (16 bits) to int (32 bits).  We can assign an int to a float.
  112. We cannot assign a longer type to a shorter or a float to an int,
  113. unless we use a cast.  With casting one has to be careful, because of
  114. potential loss of precision, for example, in stuffing 32 bits into 16.
  115. Similarly, we can assign class object references to references to a
  116. base class, but not the other way around without casting.
  117.  
  118. Given this notion of assignment, and an actual method call, how does
  119. Java decide which method to call?  First of all, it finds all methods
  120. that have the correct name, the correct number of parameters, and
  121. parameters that are of types that can be assigned the values of the
  122. arguments.  If only one method matches, then that is the method that
  123. is invoked.
  124.  
  125. If there's more than one method in the set under consideration, then
  126. the compiler goes through and finds methods for which all the
  127. parameter types are assignable to another method's parameter types in
  128. the set, and removes that other method from the set of methods being
  129. considered.  The method removed is considered "less specific".
  130.  
  131. If the result of this process is a single method, then that method is
  132. invoked.  If there's more than one method left, the call is ambiguous.
  133.  
  134. To illustrate these ideas, consider another example:
  135.  
  136.         public class test2 {
  137.  
  138.                 public static void f1(int i, int j) {}
  139.                 public static void f1(int i, short j) {}
  140.  
  141.                 public static void f2(long i, long j) {}
  142.                 public static void f2(int i, int j) {}
  143.  
  144.                 public static void f3(short i, short j) {}
  145.  
  146.                 public static void f4(double i, float j) {}
  147.                 public static void f4(float i, double j) {}
  148.  
  149.                 public static void main(String args[])
  150.                 {
  151.                 
  152.                         int i = 0;
  153.                         short s = 0;
  154.  
  155.                         f1(i, s);
  156.  
  157.                         f2(i, s);
  158.  
  159.                         f3(i, s);
  160.  
  161.                         f4(i, s);
  162.                 }
  163.  
  164.         }
  165.  
  166. The f1() call invokes f1(int, short) and is an exact match.
  167.  
  168. The f2() call invokes f2(int, int) because f2(int, int) has parameter
  169. types that are assignable to f2(long, long) and f2(long, long) is
  170. therefore removed from the set.
  171.  
  172. The f3() call is an error because an int for the first parameter
  173. cannot be assigned to a short.
  174.  
  175. The f4() call is ambiguous because both methods can be called and
  176. neither can be removed from the set of possible methods to call
  177. because neither has parameter types assignable to the other.
  178.  
  179. Coming back to C++ for a moment, it's fair to say that the equivalent
  180. argument matching rules in that language are significantly more
  181. complicated, reflecting a more complex language in general.  For
  182. example, consider a case like:
  183.  
  184.         class String {
  185.         public:
  186.                 String(char);
  187.         };
  188.  
  189. where a constructor is defined to create a String from a character.
  190. In C++, usage like:
  191.  
  192.         String s(37);
  193.  
  194. is valid, with the integer constant 37 being demoted to a char and
  195. then the constructor invoked.  Whether a user intended this or not is
  196. not clear, given that usage such as:
  197.  
  198.         String s(12345);
  199.  
  200. is a problem when chars are 8 bits.
  201.  
  202. There's no magic formula for avoiding problems with method
  203. overloading, except perhaps to follow the general rule of avoiding
  204. cleverness.  If a reader of your code can't quickly tell which method
  205. is invoked in a given case, then it might be worth reworking the code
  206. or at least adding a comment about its operation.
  207.  
  208.  
  209. INTRODUCTION TO APPLET PROGRAMMING PART 2 - DRAWING
  210.  
  211. In previous issues we gave a simple example of an applet, and talked
  212. about the handshaking that goes on between an applet and the applet
  213. viewer or Web browser.  As you recall, an applet is not a standalone
  214. Java program of the sort we've presented examples of here, but instead
  215. is a program that runs in a particular context, invoked via a Web
  216. browser or applet viewer program.
  217.  
  218. We will continue our discussion by talking about drawing in an applet,
  219. things like lines and boxes and colors and fonts.  To illustrate these
  220. ideas, let's look at an actual applet:
  221.  
  222.         import java.applet.*;
  223.         import java.awt.*;
  224.  
  225.         public class test1 extends Applet {
  226.  
  227.                 public void paint(Graphics g)
  228.                 {
  229.                         g.setColor(Color.red);
  230.                         g.fillOval(20, 20, 350, 200);
  231.  
  232.                         g.setColor(Color.green);
  233.  
  234.                         g.setFont(new Font("Helvetica", Font.ITALIC, 36));
  235.                         g.drawString("This is a test", 80, 120);
  236.  
  237.                         //g.setColor(Color.blue);
  238.                         g.setColor(new Color(0, 0, 223));
  239.                         g.drawRect(20, 20, 350, 200);
  240.                 }
  241.  
  242.         }
  243.  
  244. that is invoked via a browser or applet viewer using the HTML code:
  245.  
  246.         <html>
  247.         <body>
  248.  
  249.         <applet code="test1.class" width=400 height=400>
  250.         </applet>
  251.  
  252.         </body>
  253.         </html>
  254.  
  255. The parameters passed in to the applet set the bounding box (400 x 400
  256. in this example) within which the applet will function.
  257.  
  258. As we've discussed previously, an applet has no main() method, and the
  259. paint() method is part of the handshaking protocol for an applet.
  260. paint() is called when the applet needs to be drawn.
  261.  
  262. The first thing that paint() does is to set a color for drawing.  A
  263. color like "red" is a static data member of the Color class found in
  264. the Abstract Windowing Toolkit (AWT) in Java.  It's also possible to
  265. specify your own color, as we illustrate later in the example:
  266.  
  267.         g.setColor(new Color(0, 0, 223));
  268.  
  269. where (0, 0, 223) are red/green/blue values 0-255.  This particular
  270. color is a dark shade of blue.
  271.  
  272. After setting the color, we draw a filled oval, starting at position
  273. (20, 20) relative to the bounding box we've established.  The oval has
  274. a width of 350 and a height of 200.
  275.  
  276. We now have a red oval on the screen, and we change the drawing color
  277. to green and draw some text.  In this example, the Helvetica font is
  278. used and the text is drawn in italics using 36-point letters.  The
  279. string originates at (80, 120) in the bounding box.
  280.  
  281. Finally, we draw a box around the oval, using the color we've created
  282. from RGB values.
  283.  
  284. The Graphics class in java.awt has a variety of methods for drawing
  285. lines, rectangles, ovals, polygons, and strings, with or without
  286. filling.  There are also various methods for getting and setting colors
  287. and fonts.
  288.  
  289. The Color class has a set of standard colors defined, and methods for
  290. creating your own colors or querying properties of existing colors.
  291.  
  292. The Font class has similar methods for fonts, and there is also a
  293. FontMetrics class for determining the metrics of a specified font,
  294. such as might be used to compute the width of a string displayed in a
  295. given font.
  296.  
  297.  
  298. PERFORMANCE - PRIMITIVE TYPES VS. WRAPPERS
  299.  
  300. In Java all class types are derived from the base class Object.
  301. Primitive types such as int or double are not class types and do not
  302. have this property.  But they do have class type wrappers, that can be
  303. used to represent the primitive type and hence plug in to the Object
  304. hierarchy.  For example, the wrapper for int is Integer:
  305.  
  306.         Integer x = new Integer(37);
  307.  
  308.         Object p = x;
  309.  
  310. In this example we've taken an integer constant (37) and created a
  311. class object instance to represent this value.  The object instance
  312. can be assigned to an Object reference and manipulated in various ways.
  313.  
  314. Wrappers have some overhead associated with them.  They offer
  315. generality at the cost of inconvenience in digging out the value:
  316.  
  317.         int i = ((Integer)p).intValue();
  318.  
  319. and there are some space costs as well.  To more closely examine this
  320. latter point, we can write a program that allocates a vector of ints
  321. or int wrappers, and compute the size of each vector element:
  322.  
  323.         public class test1 {
  324.  
  325.                 public static final int N = 25000;
  326.  
  327.                 public static long freemem()
  328.                 {
  329.                         System.gc();
  330.                         return Runtime.getRuntime().freeMemory();
  331.                 }
  332.  
  333.                 // ints without wrappers
  334.  
  335.                 public static void test01()
  336.                 {
  337.                         long start_mem = freemem();
  338.  
  339.                         int vec[] = new int[N];
  340.  
  341.                         for (int i = 0; i < N; i++)
  342.                                 vec[i] = i;
  343.  
  344.                         long end_mem = freemem();
  345.                         long n = (start_mem - end_mem) / N;
  346.  
  347.                         System.out.println("bytes per element = " + n);
  348.                 }
  349.  
  350.                 // ints with wrappers
  351.  
  352.                 public static void test02()
  353.                 {
  354.                         long start_mem = freemem();
  355.  
  356.                         Integer vec[] = new Integer[N];
  357.  
  358.                         for (int i = 0; i < N; i++)
  359.                                 vec[i] = new Integer(i);
  360.  
  361.                         long end_mem = freemem();
  362.                         long n = (start_mem - end_mem) / N;
  363.  
  364.                         System.out.println("bytes per element = " + n);
  365.                 }
  366.  
  367.                 // driver
  368.  
  369.                 public static void main(String args[])
  370.                 {
  371.                         test01();
  372.                         test02();
  373.                 }
  374.  
  375.         }
  376.  
  377. This program uses a system method freeMemory() that returns the amount
  378. of memory currently free.  We force a garbage collection via
  379. System.gc() to make the figure more reliable.  As we mentioned in
  380. issue #004, this technique for determining memory use per element
  381. should be used cautiously.
  382.  
  383. When we run this program, it reports 4 bytes used per element without
  384. wrappers, and 16 per element with a wrapper.  A wrapped double reports
  385. as 24 bytes per element, with the actual double value as 64 bits (8
  386. bytes).  The space overhead of wrappers goes to support things like
  387. garbage collection.
  388.  
  389. Wrappers have considerable advantages in that primitive types can be
  390. treated in a way similar to class types.  See for example the
  391. discussion on page 243 of Arnold & Gosling's book "The Java
  392. Programming Language" (Addison-Wesley).
  393.  
  394. But they do take extra space and time, which may be an issue in some
  395. circumstances.
  396.  
  397.  
  398. ACKNOWLEDGEMENTS
  399.  
  400. Thanks to Thierry Ciot, Irv Kanode, Mike Paluka, and Alan Saldanha for
  401. help with proofreading.
  402.  
  403.  
  404. SUBSCRIPTION INFORMATION / BACK ISSUES
  405.  
  406. To subscribe to the newsletter, send mail to majordomo@world.std.com
  407. with this line as its message body:
  408.  
  409. subscribe java_letter
  410.  
  411. Back issues are available via FTP from:
  412.  
  413.         rmii.com /pub2/glenm/javalett
  414.  
  415. or on the Web at:
  416.  
  417.         http://www.rmii.com/~glenm
  418.  
  419. There is also a C++ newsletter.  To subscribe to it, say:
  420.  
  421. subscribe c_plus_plus
  422.  
  423. using the same majordomo@world.std.com address.
  424.  
  425. -------------------------
  426.  
  427. Copyright (c) 1996 Glen McCluskey.  All Rights Reserved.
  428.  
  429. This newsletter may be further distributed provided that it is copied
  430. in its entirety, including the newsletter number at the top and the
  431. copyright and contact information at the bottom.
  432.  
  433. Glen McCluskey & Associates
  434. Professional Computer Consulting
  435. Internet: glenm@glenmccl.com
  436. Phone: (800) 722-1613 or (970) 490-2462
  437. Fax: (970) 490-2463
  438. FTP: rmii.com /pub2/glenm/javalett (for back issues)
  439. Web: http://www.rmii.com/~glenm
  440.